# encoding: utf-8
class RangeWordController < ApplicationController

  def index
    @books = Book.all
    @dictionaries = Dictionary.all
  end

  #get /range
  def range
    part_a = params[:part_a].map{|x| x.to_i}
    if params[:part_b]
      part_b = params[:part_b].map{|x| x.to_i}
    else
      part_b = []
    end
    type = params[:type]
    name = params[:name]
    description = params[:description]
    output = params[:output]

    case type
      when 'union'
        result = Book.union(part_a,part_b)
      when 'subtract'
        result = Book.subtract(part_a,part_b)
      when 'intersect'
        result = Book.intersect(part_a,part_b)
      when 'difference'
        result = Book.difference(part_a,part_b)
      else
        result = []
    end
    if result.blank?
      flash[:error] = "结果集为空"
      render :text => Oj.dump({"status" => 1})
    end

    dic_json = {
        "part_a" => part_a.to_json,
        "type" => type,
        "part_b" => part_b.to_json
    }


    dic = Dictionary.create( :name => name,
                             :description => description,
                             :dictionary_json => Oj.dump(dic_json),
                             :word_json => Oj.dump(result))
    if dic.valid?
      if output == "true"
        # send_data Dictionary.output_csv(dic.id),
        #          filename: "#{name}.csv",
        #          type: "text/csv"
        render :json => Oj.dump({"save_id" => dic.id,"save_name" => dic.name,"status" => 2})

      else
        render :json => Oj.dump({"save_id" => dic.id,"save_name" => dic.name,"status" => 1})
      end
    else
      # render json: {"status" => 0}
      render :json => Oj.dump({"status" => 0})
    end
  end

  # get /out/:id
  def out
    id = params[:id].to_i
    dic = Dictionary.find(id)
    send_data Dictionary.output_csv(dic.id),
              filename: "#{dic.name}.csv",
              type: "text/csv"

  end



end
